package com.tianquan.client.loadBalan.strategy;

import com.tianquan.client.registry.ClientInstanceManager;
import com.tianquan.common.instance.ServiceInstance;

import java.util.Random;
import java.util.Set;

/**
 * @Author: tianquan
 * @date: 2024-11-04  12:22
 * @Description: 随机负载均衡器
 */
public class RandomLoadBalancer implements LoadBalancer {

    private final Random random = new Random();

    @Override
    public ServiceInstance choose(String serviceName) {
        // 获取指定的服务列表
        Set<ServiceInstance> instance = ClientInstanceManager.getInstance(serviceName);
        System.out.println(instance);
        if (instance == null || instance.isEmpty()) {
            return null;
        }
        // 随机选择一个服务实例
        int index = random.nextInt(instance.size());
        return instance.stream().skip(index).findFirst().orElse(null);
    }

}
